<template>
  <a-upload name="avatar" :headers="headers" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
    action="http://localhost:9090/file/upload" :before-upload="beforeUpload" @change="handleChange">
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 100%" />
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">Upload</div>
    </div>
  </a-upload>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      imageUrl: '',
      headers: {
        "X-Requested-With": null
      }
    };
  },
  methods: {
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.imageUrl = info.file.response.url;
        this.loading = false;
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG/PNG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 10MB!');
      }
      return isJpgOrPng && isLt2M;
    },
  },
};
</script>

<style>
.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}
</style>










<template>
  <div>
    <input type="file" @change="handleFileChange" accept="image/*">
    <button @click="uploadImage">上传图片</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      file: null,
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
    },
    uploadImage() {
      if (!this.file) {
        alert('请选择一个图片文件');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.file);

      // 使用原生XMLHttpRequest发送请求
      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://localhost:9090/file/upload', true);
      xhr.onload = () => {
        if (xhr.status === 200) {
          // 请求成功
          alert('图片上传成功');
          console.log(xhr.responseText);
        } else {
          // 请求失败
          alert('图片上传失败');
        }
      };
      xhr.onerror = () => {
        alert('网络错误');
      };
      xhr.send(formData);
    },
  },
};
</script>